package ansible

import (
	"hulk-api/util/common"
	"os"
	"log"
	"strings"
	"fmt"
	"sync"
	"time"
)

const (
	DEFAULT_PLAYBOOK_DIR = "static/ansible-playbook/"
	DEFAULT_PLAYBOOK_HOST_FILENAME = "hosts"
	DEFAULT_PLAYBOOK_YAML_FILENAME = "book.yaml"

)

type Playbook struct {
	IpLine string			`json:"ipLine"`

	WorkDir string
	Content string			`json:"content"`
	BookYaml string
	Hosts   string
	Cmdline string
	err error


}

func (p *Playbook) InitSetting() (*Playbook)  {
	if p.WorkDir == "" {
		p.WorkDir = DEFAULT_PLAYBOOK_DIR + common.GetRandomString()
		os.MkdirAll(p.WorkDir,os.ModePerm)
	}
	var err error
	err = p.setHost()
	if err != nil {
		p.err = err
		return p
	}
	err = p.setBookYaml()
	if err != nil {
		p.err = err
		return p
	}
	return p

}

func (p *Playbook) setHost() (err error){
	hostPath := p.WorkDir + "/" + DEFAULT_PLAYBOOK_HOST_FILENAME
	f,err := os.OpenFile(hostPath,os.O_RDWR | os.O_CREATE|os.O_APPEND,0666)
	if err != nil {
		log.Println(err)
		return
	}
	defer f.Close()
	for _,ip := range strings.Split(p.IpLine,",") {
		f.WriteString(ip+"\n")
	}
	return

}

func (p *Playbook) setBookYaml() (err error){
	yamlPath := p.WorkDir + "/" + DEFAULT_PLAYBOOK_YAML_FILENAME
	f,err := os.OpenFile(yamlPath,os.O_RDWR | os.O_CREATE|os.O_APPEND,0666)
	if err != nil {
		log.Println(err)
		return
	}
	defer f.Close()
	f.WriteString(p.Content)
	return
}

func (p *Playbook) Run() (string) {
	time.Sleep(3 * time.Second)  //test
	if p.err != nil {
		return p.err.Error()
	}
	defer p.destory()
	p.Cmdline = fmt.Sprintf("ansible-playbook -i %s %s ",DEFAULT_PLAYBOOK_HOST_FILENAME,DEFAULT_PLAYBOOK_YAML_FILENAME)
	c,_ := NewAnsibleCmd(p.Cmdline)
	c.SetDir(p.WorkDir)

	output := ""
	wg := sync.WaitGroup{}
	wg.Add(1)
	outputChan := make(chan string,1)

	go c.Run(&wg,outputChan)   //TODO:设计有问题

	wg.Wait()

	close(outputChan)
	for res := range outputChan {
		output = output + res
	}
	return output
}

func (p *Playbook) destory()  {

	os.RemoveAll(p.WorkDir)

}